<template>
  <div>
    <div class="row-header">
      <el-form :model="form" ref="form" label-width="50px" inline>
        <el-form-item label=" " prop="time">
          <el-date-picker
            v-model="form.time"
            type="daterange"
            range-separator="至"
            start-placeholder="提交开始时间"
            end-placeholder="提交结束时间"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" " prop="operatorNumber">
          <el-input v-model.trim="form.operatorNumber" size="small" placeholder="请输入业务号码/ICCID" style="width: 300px"/>
        </el-form-item>
        <el-form-item label=" " prop="state">
          <el-select v-model="form.state" placeholder="请选择是否次月生效">
            <el-option v-for="item in options" :value="item.value" :label="item.label" :key="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="row-form-btn">
        <el-button type="shenda" size="small" @click="page=1;initData()" icon="el-icon-search">查询</el-button>
        <el-button type="shenda" size="small" @click="resetForm('form')" icon="el-icon-refresh-right">重置</el-button>
      </div>
    </div>

    <div class="split-line"></div>
    <div class="row-main">
      <el-button type="shenda" @click="bathRetry" v-has="'oemOrderBathRetryPer'">批量重试</el-button>
      <el-table :header-cell-style="{ 'background':$store.state.app.tableBgColor,'color':'#606266' }" :data="tableData" tooltip-effect="dark" class="row-main-table" @selection-change="handleSelectionChange"
                v-loading.fullscreen="tableLoading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.2)" ref="table">
        <el-table-column
          type="selection"
          width="55"
        >
        </el-table-column>
        <el-table-column prop="cardNum" label="卡号" align="center" :fixed="$store.state.app.screenWidth<992?true:false" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="loginName" label="代理账号" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="insertTime" label="用户充值时间" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="accountName" label="通道" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="dictPayTunnelName" label="支付方式" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="price" label="订单价格" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column prop="setMealName" label="套餐名称" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <!--        <el-table-column prop="dictStatusName" label="是否次月生效" align="center" :fixed="$store.state.app.screenWidth<992?true:false" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>-->
        <el-table-column prop="dictIsPreStorageName" label="是否次月生效" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'">
          <template slot-scope="scope">
            <span
              :style="{'color':scope.row.dictIsProblemOrder==='C_YES'?'red':''}">{{ scope.row.dictIsPreStorageName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="isHide" label="订单是否已隐藏" align="center" :width="$store.state.app.screenWidth<992?'130px':'auto'">
          <template slot-scope="scope">
            <span :style="{'color':scope.row.isHide==='C_YES'?'red':''}" v-if="scope.row.isHide=='C_YES'">已隐藏</span>
            <span :style="{'color':scope.row.isHide==='C_YES'?'red':''}" v-if="scope.row.isHide!='C_YES'">未隐藏</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" :fixed="$store.state.app.screenWidth<992?true:false" :width="$store.state.app.screenWidth<992?'130px':'auto'"></el-table-column>
        <el-table-column v-has="'orderCtrl'" prop="dictStatus" label="操作" align="center">
          <template slot-scope="scope">
            <el-dropdown trigger="click">
              <div>
                <svg-icon class="el-dropdown-link" icon-class="operation"></svg-icon>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>
                  <el-button class="operation" type="text" v-has="'oprationStatusPer'" @click="doSomeAct(scope.row, 'retryOrder')" v-preventReClick>重试</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button class="operation" type="text" v-has="'refundPer'" @click="doSomeAct(scope.row, 'refundOrder')" v-preventReClick>退款</el-button>
                </el-dropdown-item>
                <el-dropdown-item>
                  <el-button class="operation" type="text" v-has="'oprationStatusPer'" @click="doSomeAct(scope.row, 'updateState')" v-preventReClick>强制更改订单状态</el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div :style="{'overflow-x': $store.state.app.screenWidth<992?'scroll':'none'}">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="page"
          :page-size="pagesize"
          class="row-main-pager"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10,20,50]"
          background>

        </el-pagination>
      </div>
    </div>

    <!--  弹窗：修改订单状态 -->
    <el-dialog
      :title="title"
      :visible.sync="updateOrderInfoDialog"
      width="500px"
      center>
      <div style="display: flex;flex-direction: column;justify-content: center;align-items: center">
        <div style="display: flex; color:red;justify-content: center;">{{ tipText }}</div>
        <div style="margin-top: 20px">
          <el-form :model="actForm" ref="actForm" :rules="actRule" label-position="right" label-width="120px">
            <el-form-item label="订单状态：" prop="orderStatus" v-if="actStatus=='updateState'">
              <el-radio-group v-model="actForm.orderStatus" size="small">
                <el-radio-button v-for="item in orderStatusOptions" :key="item.label" :label="item.label">{{ item.value }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="退款比例：" prop="rate_money" v-if="actStatus=='refundOrder'">
              <el-input v-model="actForm.rate_money" disabled></el-input>
            </el-form-item>
            <el-form-item label="退佣金比例：" prop="rate_brokerage" v-if="actStatus=='refundOrder'">
              <el-input v-model="actForm.rate_brokerage" disabled></el-input>
            </el-form-item>
            <el-form-item label="支付流水号：" prop="tranId" v-if="actStatus=='updateOrderNo'">
              <el-input v-model="actForm.tranId" style="width: 300px"></el-input>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetActForm('actForm')">取 消</el-button>
        <el-button type="primary" @click="onSubmit('actForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  orderManagement,
  getProcessingOrderRemark,
  refreshOrder,
  backUserMoneyByOrderId,
  updateOrderStatus,
  orderRefundCheck, customerRefund,
  batchRetryRecords, customerRefundForPrice,
} from '@/api/getData'

export default {
  name: 'processingOrder',
  data() {
    return {
      form: {
        time: '',
        state: '',
        operatorNumber: '',
      },
      options: [
        {value: '', label: '请选择是否次月生效'},
        {value: 'YES', label: '是'},
        {value: 'NO', label: '否'},
      ],
      tableData: [],
      tableLoading: false,
      page: 1,
      pagesize: 10,
      total: 0,
      actForm: {
        orderStatus: '',          //订单状态
      },
      actRule: {
        orderStatus: [{required: true, message: '请选择订单状态', trigger: 'change'}],
        rate_money: [
          {required: true, message: '请填写订单退款比例', trigger: 'blur'},
          {pattern: /^100|(\d){1,2}|[0]\.\d{1,2}|[1-9]{1}[0-9]{0,1}$/, message: '格式：1 - 100的整数', trigger: 'blur'},
        ],
        rate_brokerage: [
          {required: true, message: '请填写订单退佣金比例', trigger: 'blur'},
          {pattern: /^100|(\d){1,2}|[0]\.\d{1,2}|[1-9]{1}[0-9]{0,1}$/, message: '格式：1 - 100的整数', trigger: 'blur'},
        ],
        tranId: [
          {required: true, message: '请修改支付流水号', trigger: 'change'}
        ]
      },
      tipText: '',
      title: '',
      updateOrderInfoDialog: false,
      orderStatusOptions: [       //订单状态
        {value: '待充送', label: '1'},
        {value: '已付款', label: '2'},
        {value: '待付款', label: '3'},
        // { value: '次月生效', label: '4' },
        // { value: '本月生效', label: '5' },
        {value: '退款成功', label: '6'},
      ],  //订单状态
      bathRetryList: [],
    }
  },
  mounted() {
    this.initData();
  },
  methods: {
    handleSelectionChange(val) {
      this.bathRetryList = val;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.table.toggleRowSelection(row);
        });
      } else {
        this.$refs.table.clearSelection();
      }

    },
    //点击批量重试按钮
    bathRetry() {
      if (this.bathRetryList.length == 0) {
        this.$message.error("请先勾选待重试的数据！");
        return false;
      }
      let flag = false;
      for(let item of this.bathRetryList){
        if(item.isHide=='C_YES'){
          flag = true;
          break;
        }
      }
      if(flag){
        this.$message.error('当前部分订单在隐藏状态下，故不支持重试功能');
        return false;
      }
      this.tableLoading = true;
      this.$confirm(`此操作将对选中的${this.bathRetryList.length}条数据进行批量重试, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let arr = [];
        for (let item of this.bathRetryList) {
          arr.push(item.id)
        }
        let res = await batchRetryRecords({ids: arr})
        if(res.code==10000){
          this.$message({
            type: 'success',
            message: '批量重试数据已提交'
          })
          setTimeout(()=>{
            this.initData();
          },1000)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消批量重试'
        });
      });
    },
    async initData() {
      let startTime = null
      let endTime = null
      if (this.form.time && this.form.time.length == 2) {
        startTime = this.form.time[0];
        endTime = this.form.time[1];
      }
      let cardNum = this.form.operatorNumber
      this.tableLoading = true;
      const returnData = await orderManagement({
          beginTime: startTime,                           //起始时间
          endTime: endTime,                               //结束时间
          cardNum: cardNum,                               //业务号码
          loginName: '',                                  //代理账号
          dictStatus: 'USER_ORDER_RUNNING',               //订单状态
          accountId: '',                                  //通道id
          setMealHeadId: '',                              //套餐大类id
          setMealId: '',                                  //套餐小类id
          dictIsPreStorage: this.form.state,              //是否次月生效
          transactionId: '',                              //交易流水号
          amount: '',                                     //连续充值次数
          isAllOrder: true,
          page: {
            current: this.page + '',
            size: this.pagesize + '',
            ascs: this.ascs,
            descs: this.descs
          }
        },
        {
          obj: this,
          key: 'tableLoading'
        })
      this.tableData = []
      this.paramOrResponse = [];
      if (returnData._result) {
        this.total = returnData.data.total
        // this.tableData = new Array(...returnData.data.records);
        for (let item of returnData.data.records) {
          item.remark = '';
          this.tableData.push(item);
          this.paramOrResponse.push(item.id)
        }
        this.getRemark();
      }
      this.tableLoading = false
    },
    async getRemark() {
      let returnData = await getProcessingOrderRemark({
        paramOrResponse: this.paramOrResponse
      })
      if (returnData._result) {
        if (returnData.data) {
          returnData.data.forEach((item, i) => {
            this.tableData[i].remark = item;
          })
        }
      }
    },
    handleSizeChange(val) {
      this.page = 1;
      this.pagesize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      this.page = val;
      this.initData();
    },
    async doSomeAct(item, state) {
      this.actStatus = state;
      this.orderId = item.id;
      this.pagekey = await this.$getPageKey();
      switch (state) {
        case 'updateState':
          this.title = '修改订单状态';
          this.updateOrderInfoDialog = true;
          this.tipText = `【※修改订单状态为高风险操作※】请谨慎操作！！！！当前订单状态：${item.dictStatusName}`
          break;
        case 'refundOrder':
          this.title = '订单退款';
          this.updateOrderInfoDialog = true;
          this.actForm.rate_money = 100;
          this.actForm.rate_brokerage = 100;
          this.tipText = '【※订单退款为高风险操作※】请谨慎操作！！！！'
          break;
        case 'retryOrder':
          if(item.isHide=='C_YES'){
            this.$message.error('当前订单隐藏状态下不支持重试返佣功能');
            return false;
          }
          this.$confirm('重试后会为此卡添加流量，确认重新刷新么？', '※高风险操作 【重试】※ ', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            refreshOrder({id: this.orderId, pagekey: this.pagekey}).then(v => {
              backUserMoneyByOrderId({id: this.orderId}).then(v => {
                if (v.code === 10000) {
                  this.$message.success("操作成功!")
                }
                this.initData()
              })
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作'
            });
          });
          break;
      }
    },
    resetActForm(form) {
      this.$refs[form].resetFields();
      this.updateOrderInfoDialog = false
    },

    onSubmit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          switch (this.actStatus) {
            case 'updateState':     //修改订单状态
              this.doUpdateOrderStatus();
              break;
            case 'refundOrder':     //订单退款
              this.doOrderRefund();
              break;
          }
        }
      })
    },
    //弹窗--修改订单状态
    doUpdateOrderStatus() {
      let status = this.orderStatusOptions.filter(item => {
        return item.label == this.actForm.orderStatus;
      })
      this.$confirm('是否继续将当前订单状态修改为：' + status[0].value + ' ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await updateOrderStatus({id: this.orderId, dictStatus: this.actForm.orderStatus}, {
          pagekey: this.pagekey
        }).then(v => {
          this.updateOrderInfoDialog = false;
          if (v._result) {
            this.$message.success("更改成功!");
            this.initData()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    //弹窗--订单退款
    async doOrderRefund() {

      let check = await orderRefundCheck({id: this.orderId});
      if (check._result) {
        let tipText = '';
        if (check.data.isThirdFlag) {
          tipText = '该订单为第三方订单，'
        }
        if (check.data.notFindDueTime) {
          tipText = '该订单未检索到有效期，'
        }
        if (check.data.errorMessage == '' || check.data.errorMessage == undefined) {
          if (tipText != '') {
            this.$confirm(`${tipText}是否继续对当前订单执行退款？`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.doRefund()
            }).catch(() => {

            });
          } else if (tipText == '') {
            this.doRefund()
          }
        } else if (check.data.errorMessage != '' && check.data.errorMessage != undefined) {
          this.$alert(`${tipText}${check.data.errorMessage}`, '提示', {
            confirmButtonText: '确定',
            callback: action => {
              this.updateOrderInfoDialog = false;
            }
          });
        }
      }
    },
    async doRefund() {
      let pagekey = await this.$getPageKey();
      this.$confirm('确认退款么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        customerRefundForPrice({
          proportion: this.actForm.rate_money,
          customerOrderId: this.orderId,
          backUserProportion: this.actForm.rate_brokerage,
          refund: '',
        }, {pagekey}).then(v => {
          this.updateOrderInfoDialog = false;
          if (v._result) {
            this.$message.success("请到退款记录中查看")
            this.initData()
          }
        })
      }).catch(() => {

      });
    },
    resetForm(form) {
      this.$refs.form.resetFields();
    }
  }
}
</script>
